/**
 * 存储管理器 - 图片视频下载器
 * 负责处理数据存储、设置管理、下载历史等功能
 */

/**
 * 存储管理器类
 */
export class StorageManager {
    constructor() {
        this.defaultSettings = {
            // 下载设置
            downloadPath: 'downloads',
            filenamePattern: '{filename}',
            maxConcurrent: 3,
            maxFileSize: 100 * 1024 * 1024, // 100MB

            // 界面设置
            showNotifications: true,
            autoScan: true,
            theme: 'light',
            language: 'zh-CN',

            // 高级设置
            enableLogging: false,
            saveDownloadHistory: true,
            maxHistoryItems: 1000,

            // 文件类型设置
            supportedImageFormats: ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'],
            supportedVideoFormats: ['mp4', 'webm', 'avi', 'mov', 'mkv'],

            // 网站特定设置
            siteSettings: {}
        };
    }

    /**
     * 初始化存储管理器
     */
    async init() {
        console.log('初始化存储管理器...');

        // 确保默认设置存在
        await this.ensureDefaultSettings();

        console.log('存储管理器初始化完成');
    }

    /**
     * 确保默认设置存在
     */
    async ensureDefaultSettings() {
        try {
            const currentSettings = await this.getSettings();
            const mergedSettings = this.mergeSettings(this.defaultSettings, currentSettings);

            if (JSON.stringify(currentSettings) !== JSON.stringify(mergedSettings)) {
                await this.updateSettings(mergedSettings);
            }
        } catch (error) {
            console.error('确保默认设置失败:', error);
            // 如果获取设置失败，直接设置默认值
            await this.updateSettings(this.defaultSettings);
        }
    }

    /**
     * 合并设置
     */
    mergeSettings(defaults, current) {
        const merged = { ...defaults };

        for (const key in current) {
            if (current.hasOwnProperty(key)) {
                if (typeof current[key] === 'object' && !Array.isArray(current[key])) {
                    merged[key] = this.mergeSettings(defaults[key] || {}, current[key]);
                } else {
                    merged[key] = current[key];
                }
            }
        }

        return merged;
    }

    /**
     * 获取设置
     */
    async getSettings() {
        try {
            return new Promise((resolve, reject) => {
                chrome.storage.sync.get(['settings'], (result) => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve(result.settings || this.defaultSettings);
                    }
                });
            });
        } catch (error) {
            console.error('获取设置失败:', error);
            return this.defaultSettings;
        }
    }

    /**
     * 更新设置
     */
    async updateSettings(newSettings) {
        try {
            return new Promise((resolve, reject) => {
                chrome.storage.sync.set({ settings: newSettings }, () => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve(true);
                    }
                });
            });
        } catch (error) {
            console.error('更新设置失败:', error);
            throw error;
        }
    }

    /**
     * 获取特定设置项
     */
    async getSetting(key, defaultValue = null) {
        try {
            const settings = await this.getSettings();
            return settings[key] !== undefined ? settings[key] : defaultValue;
        } catch (error) {
            console.error(`获取设置项失败: ${key}`, error);
            return defaultValue;
        }
    }

    /**
     * 更新特定设置项
     */
    async updateSetting(key, value) {
        try {
            const settings = await this.getSettings();
            settings[key] = value;
            await this.updateSettings(settings);
            return true;
        } catch (error) {
            console.error(`更新设置项失败: ${key}`, error);
            throw error;
        }
    }

    /**
     * 重置设置
     */
    async resetSettings() {
        try {
            await this.updateSettings(this.defaultSettings);
            console.log('设置已重置为默认值');
            return true;
        } catch (error) {
            console.error('重置设置失败:', error);
            throw error;
        }
    }

    /**
     * 获取下载历史
     */
    async getDownloadHistory(limit = null) {
        try {
            return new Promise((resolve, reject) => {
                chrome.storage.local.get(['downloadHistory'], (result) => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        let history = result.downloadHistory || [];

                        // 按时间倒序排列
                        history.sort((a, b) => b.timestamp - a.timestamp);

                        // 限制数量
                        if (limit && history.length > limit) {
                            history = history.slice(0, limit);
                        }

                        resolve(history);
                    }
                });
            });
        } catch (error) {
            console.error('获取下载历史失败:', error);
            return [];
        }
    }

    /**
     * 添加下载历史
     */
    async addDownloadHistory(downloadItem) {
        try {
            const saveHistory = await this.getSetting('saveDownloadHistory', true);
            if (!saveHistory) {
                return;
            }

            const maxHistoryItems = await this.getSetting('maxHistoryItems', 1000);
            const history = await this.getDownloadHistory();

            // 创建历史记录项
            const historyItem = {
                id: downloadItem.id,
                url: downloadItem.url,
                filename: downloadItem.filename,
                type: downloadItem.type,
                size: downloadItem.fileSize || 0,
                state: downloadItem.state,
                timestamp: Date.now(),
                startTime: downloadItem.startTime,
                endTime: downloadItem.endTime || null
            };

            // 添加到历史记录开头
            history.unshift(historyItem);

            // 限制历史记录数量
            if (history.length > maxHistoryItems) {
                history.splice(maxHistoryItems);
            }

            // 保存到存储
            await new Promise((resolve, reject) => {
                chrome.storage.local.set({ downloadHistory: history }, () => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve(true);
                    }
                });
            });

            console.log('下载历史已更新');

        } catch (error) {
            console.error('添加下载历史失败:', error);
        }
    }

    /**
     * 更新下载历史项
     */
    async updateDownloadHistory(downloadId, updates) {
        try {
            const history = await this.getDownloadHistory();
            const index = history.findIndex(item => item.id === downloadId);

            if (index !== -1) {
                history[index] = { ...history[index], ...updates };

                await new Promise((resolve, reject) => {
                    chrome.storage.local.set({ downloadHistory: history }, () => {
                        if (chrome.runtime.lastError) {
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(true);
                        }
                    });
                });
            }

        } catch (error) {
            console.error('更新下载历史失败:', error);
        }
    }

    /**
     * 删除下载历史项
     */
    async deleteDownloadHistory(downloadId) {
        try {
            const history = await this.getDownloadHistory();
            const filteredHistory = history.filter(item => item.id !== downloadId);

            await new Promise((resolve, reject) => {
                chrome.storage.local.set({ downloadHistory: filteredHistory }, () => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve(true);
                    }
                });
            });

            console.log('下载历史项已删除');

        } catch (error) {
            console.error('删除下载历史失败:', error);
        }
    }

    /**
     * 清空下载历史
     */
    async clearDownloadHistory() {
        try {
            await new Promise((resolve, reject) => {
                chrome.storage.local.remove(['downloadHistory'], () => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve(true);
                    }
                });
            });

            console.log('下载历史已清空');

        } catch (error) {
            console.error('清空下载历史失败:', error);
        }
    }

    /**
     * 获取网站特定设置
     */
    async getSiteSettings(domain) {
        try {
            const settings = await this.getSettings();
            return settings.siteSettings[domain] || {};
        } catch (error) {
            console.error('获取网站设置失败:', error);
            return {};
        }
    }

    /**
     * 更新网站特定设置
     */
    async updateSiteSettings(domain, siteSettings) {
        try {
            const settings = await this.getSettings();
            settings.siteSettings[domain] = { ...settings.siteSettings[domain], ...siteSettings };
            await this.updateSettings(settings);

            console.log(`网站设置已更新: ${domain}`);

        } catch (error) {
            console.error('更新网站设置失败:', error);
        }
    }

    /**
     * 获取统计数据
     */
    async getStatistics() {
        try {
            const history = await this.getDownloadHistory();
            const stats = {
                totalDownloads: history.length,
                successfulDownloads: history.filter(item => item.state === 'complete').length,
                failedDownloads: history.filter(item => item.state === 'interrupted').length,
                totalSize: history.reduce((sum, item) => sum + (item.size || 0), 0),
                imageDownloads: history.filter(item => item.type === 'image').length,
                videoDownloads: history.filter(item => item.type === 'video').length,
                averageDownloadTime: 0
            };

            // 计算平均下载时间
            const completedDownloads = history.filter(item =>
                item.state === 'complete' && item.startTime && item.endTime
            );

            if (completedDownloads.length > 0) {
                const totalTime = completedDownloads.reduce((sum, item) =>
                    sum + (item.endTime - item.startTime), 0
                );
                stats.averageDownloadTime = totalTime / completedDownloads.length;
            }

            return stats;

        } catch (error) {
            console.error('获取统计数据失败:', error);
            return {
                totalDownloads: 0,
                successfulDownloads: 0,
                failedDownloads: 0,
                totalSize: 0,
                imageDownloads: 0,
                videoDownloads: 0,
                averageDownloadTime: 0
            };
        }
    }

    /**
     * 导出数据
     */
    async exportData() {
        try {
            const settings = await this.getSettings();
            const history = await this.getDownloadHistory();
            const stats = await this.getStatistics();

            const exportData = {
                version: '1.0.0',
                exportDate: new Date().toISOString(),
                settings: settings,
                downloadHistory: history,
                statistics: stats
            };

            return exportData;

        } catch (error) {
            console.error('导出数据失败:', error);
            throw error;
        }
    }

    /**
     * 导入数据
     */
    async importData(data) {
        try {
            // 验证数据格式
            if (!data.version || !data.settings) {
                throw new Error('无效的数据格式');
            }

            // 导入设置
            if (data.settings) {
                await this.updateSettings(data.settings);
            }

            // 导入下载历史
            if (data.downloadHistory && Array.isArray(data.downloadHistory)) {
                await new Promise((resolve, reject) => {
                    chrome.storage.local.set({ downloadHistory: data.downloadHistory }, () => {
                        if (chrome.runtime.lastError) {
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(true);
                        }
                    });
                });
            }

            console.log('数据导入成功');
            return true;

        } catch (error) {
            console.error('导入数据失败:', error);
            throw error;
        }
    }

    /**
     * 备份数据
     */
    async backupData() {
        try {
            const data = await this.exportData();
            const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });

            const url = URL.createObjectURL(blob);
            const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
            const filename = `download-manager-backup-${timestamp}.json`;

            // 触发下载
            chrome.downloads.download({
                url: url,
                filename: filename,
                saveAs: true
            });

            // 清理URL
            setTimeout(() => URL.revokeObjectURL(url), 1000);

            console.log('数据备份已创建');

        } catch (error) {
            console.error('备份数据失败:', error);
            throw error;
        }
    }

    /**
     * 清理过期数据
     */
    async cleanupExpiredData() {
        try {
            const maxHistoryItems = await this.getSetting('maxHistoryItems', 1000);
            const history = await this.getDownloadHistory();

            if (history.length > maxHistoryItems) {
                const cleanedHistory = history.slice(0, maxHistoryItems);

                await new Promise((resolve, reject) => {
                    chrome.storage.local.set({ downloadHistory: cleanedHistory }, () => {
                        if (chrome.runtime.lastError) {
                            reject(new Error(chrome.runtime.lastError.message));
                        } else {
                            resolve(true);
                        }
                    });
                });

                console.log(`清理了 ${history.length - maxHistoryItems} 条过期历史记录`);
            }

        } catch (error) {
            console.error('清理过期数据失败:', error);
        }
    }

    /**
     * 获取存储使用情况
     */
    async getStorageUsage() {
        try {
            return new Promise((resolve, reject) => {
                chrome.storage.local.getBytesInUse(null, (bytesInUse) => {
                    if (chrome.runtime.lastError) {
                        reject(new Error(chrome.runtime.lastError.message));
                    } else {
                        resolve({
                            bytesUsed: bytesInUse,
                            bytesUsedFormatted: this.formatBytes(bytesInUse),
                            percentage: (bytesInUse / (1024 * 1024 * 5)) * 100 // 假设5MB限制
                        });
                    }
                });
            });
        } catch (error) {
            console.error('获取存储使用情况失败:', error);
            return {
                bytesUsed: 0,
                bytesUsedFormatted: '0 B',
                percentage: 0
            };
        }
    }

    /**
     * 格式化字节数
     */
    formatBytes(bytes) {
        if (bytes === 0) return '0 B';

        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    /**
     * 监听存储变化
     */
    onStorageChanged(callback) {
        chrome.storage.onChanged.addListener((changes, namespace) => {
            callback(changes, namespace);
        });
    }

    /**
     * 销毁存储管理器
     */
    destroy() {
        console.log('存储管理器已销毁');
    }
} 